package scau.erps.service.impl;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.service.IdEntityService;

import scau.erps.app.Erps;
import scau.erps.entity.Bidding;
import scau.erps.entity.TeamOrder;
import scau.erps.entity.SystemOrder;
import scau.erps.service.BiddingService;
import scau.erps.service.TeamOrderService;
import scau.erps.util.CalculateQuarter;

/**
 * 小组订单服务实现类
 * @author DCJ
 *
 */
public class TeamOrderServiceImpl extends IdEntityService<TeamOrder> implements TeamOrderService {

	@Override
	public void save(TeamOrder ordar) {
		this.dao().insert(ordar);
		
	}

	@Override
	public int recordOrders() {
		BiddingService biddingService = Erps.getIocInstance().get(BiddingServiceImpl.class);	
		int team_Id = Erps.getCurrentTeam().getId();
		String year = CalculateQuarter.getCurrentYear(Erps.getSand().getTime());						
		List<Bidding> list  = biddingService.getBiddings(team_Id, year, "竞价成功");
		int i = list.size();
		SystemOrder systemOrder = null;
		for (Bidding bidding : list) {
			systemOrder = this.dao().fetch(SystemOrder.class, bidding.getOrder_Id());			
			TeamOrder order = new TeamOrder();
			order.setTeam_Id(team_Id);
			order.setYear(year);			
			order.setDeliver(systemOrder.getDeliver());
			order.setIso(systemOrder.getIso());
			order.setMarket(systemOrder.getMarket());
			order.setProduct(systemOrder.getProduct());
			order.setQuantity(systemOrder.getQuantity());
			order.setReceivable(CalculateQuarter.calculateQuarter(systemOrder.getDeliver(), systemOrder.getQuarter()));
			order.setTotal(bidding.getMyprice());
			order.setStatus("未交货");
			order.setPenalty(0);
			order.setCost(0);
			this.save(order);			
		}
		return i;
		
	}

	@Override
	public List<TeamOrder> getAllOrders() {
		return this.query(null, null);
	}

	@Override
	public List<TeamOrder> getOrders(int team_Id,String year, String product, String market) {
		SqlExpressionGroup e1 = null;
		SqlExpressionGroup e2 = null;
		SqlExpressionGroup e3 = null;
		SqlExpressionGroup e4 = null;
		if(team_Id != 0){
			e1 = Cnd.exps("team_Id", "=", team_Id);			
		}
		if(year != null){
			e2 = Cnd.exps("year", "=", year);			
		}
		if(product != null){
			e3 = Cnd.exps("product", "=", product);
		}
		if(market != null){
			e4 = Cnd.exps("market", "=", market);
		}
		return this.query(Cnd.where(e1).and(e2).and(e3).and(e4), null);
	}

	@Override
	public TeamOrder getOrderById(int id) {
		return this.fetch(id);
	}

}
